from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
from app.database import get_db
from app.schemas import ContractCreate, ContractResponse
from app.services.contract_service import ContractService
from app.services.websocket_manager import websocket_manager

router = APIRouter(prefix="/api/contracts", tags=["contracts"])


@router.post("/", response_model=ContractResponse)
async def create_contract(contract_data: ContractCreate, db: AsyncSession = Depends(get_db)):
    """Create a new contract"""
    try:
        contract = await ContractService.create_contract(db, contract_data)
        
        # Send WebSocket update to user
        await websocket_manager.send_contract_update(
            contract.user_id,
            ContractResponse.from_orm(contract).dict()
        )
        
        return contract
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.get("/{contract_id}", response_model=ContractResponse)
async def get_contract(contract_id: str, db: AsyncSession = Depends(get_db)):
    """Get contract by ID"""
    contract = await ContractService.get_contract(db, contract_id)
    if not contract:
        raise HTTPException(status_code=404, detail="Contract not found")
    return contract


@router.get("/", response_model=list[ContractResponse])
async def get_contracts(user_id: str = None, limit: int = 100, db: AsyncSession = Depends(get_db)):
    """Get contracts"""
    if user_id:
        contracts = await ContractService.get_user_contracts(db, user_id, limit)
    else:
        contracts = await ContractService.get_active_contracts(db)
    
    return contracts
